package com.lyEducation.services.system;

import com.lyEducation.controllers.dto.system.SysLevelDto;
import com.lyEducation.core.system.SysLevelService;
import com.lyEducation.entities.system.SysLevelEntity;
import com.lyEducation.entities.system.SysRoleEntity;
import com.lyEducation.repository.system.SysLevelRepository;
import com.lyEducation.repository.system.SysUserRepository;
import com.lyEducation.services.AbstractServiceImpl;
import com.lyEducation.util.controllerUtil.JsonConstans;
import com.lyEducation.util.controllerUtil.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

@Service
public class SysLevelServiceImpl extends AbstractServiceImpl<SysLevelEntity, String>
    implements SysLevelService {
  @Autowired private SysLevelRepository sysLevelRepository;
  @Autowired private SysUserRepository sysUserRepository;

  @Override
  public JsonResult addSysLevel(SysLevelDto sysLevelDto) {
    //        sysRoleRepository.get
    Set<SysRoleEntity> maxRoleSet = sysUserRepository.userGetMaxLevelSysRoleSet();
    boolean isNextLevel = false;
    for (SysRoleEntity maxRole : maxRoleSet) {
      if (maxRole.getLevel() < sysLevelDto.getLevel()) {
        isNextLevel = true;
        break;
      }
    }
    if (!isNextLevel) {
      return JsonResult.putFail(JsonConstans.ERR_NOTVALID_AUTH);
    }
    List<SysLevelEntity> levelList =
        sysLevelRepository.findByFiled("level", sysLevelDto.getLevel());
    if (levelList.size() > 0) {
      return JsonResult.putFail("已存在该角色级别，无法再添加");
    }
    sysLevelRepository.save(sysLevelDto.getSysLevelEntity());
    return JsonResult.putSuccess();
  }
}
